//
//  AppDelegate.m
//  ScholarsBridge
//
//  Created by xp on 16/11/23.
//  Copyright © 2016年 mingthink. All rights reserved.
//

#import "AppDelegate.h"
#import "IQKeyboardManager.h"
#import "AppInfoService.h"
#import "TabBarController.h"
#import "LocationManager.h"
//#import "BaiduMobStat.h"
#import "PublicVC.h"
#import "ThirdShareUtil.h"
#import "ThirdPayUtil.h"
#import <UserNotifications/UserNotifications.h>
#import "JPUSHService.h"
#import <AVFoundation/AVFoundation.h>
#import "LoginVC.h"
#import "ViewController.h"
#import <WebKit/WebKit.h>
#import <sys/utsname.h>

#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")
#define NotificationChange CFSTR("com.apple.springboard.lockstate")
#define NotificationPwdUI CFSTR("com.apple.springboard.hasBlankedScreen")

static NSString *appKey = @"f71b7dbc4d4618bb7e732e75";
static NSString *channel = @"Publish channel";
//static BOOL isProduction = NO;//开发时设置NO,发布时改成YES


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //[self registerUserAgent];//修改webview userAgent区分端
    [self setNotice:application];
    [self initKeyboardManager];//键盘管理
    [self initJPushServiceWithOptions:launchOptions];
    //[ThirdPayUtil registerWXPay];//初始化微信支付
    [WXApi registerApp:[ThirdShareUtil wxAppID] withDescription:@"lqgk"];
    [self checkNetWorkConnectStatus];//网络状态检查
    //[self loadMemberAndAppInfo];//本地加载应用和个人信息
    //[self setLocationManager];//定位处理
    //[self startBaiduMobileStat];//百度统计初始化
    [ThirdShareUtil initSharePlatform];//第三方分享和登录初始化
    // [self registerProtocol];
     //[self clearWebViewCache];
    //[NSURLProtocol registerClass:WXApi.self];
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);//错误异常Log
    //监听锁屏
//    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
//    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    return YES;
}

-(void)clearWebViewCache{
    NSSet *websiteDataTypes = [NSSet setWithArray:@[
                                                    WKWebsiteDataTypeDiskCache,
                                                    WKWebsiteDataTypeOfflineWebApplicationCache,
                                                    WKWebsiteDataTypeMemoryCache,
                                                    WKWebsiteDataTypeLocalStorage,
                                                    WKWebsiteDataTypeCookies,
                                                    WKWebsiteDataTypeSessionStorage,
                                                    WKWebsiteDataTypeIndexedDBDatabases,
                                                    WKWebsiteDataTypeWebSQLDatabases
                                                    ]];
    //你可以选择性的删除一些你需要删除的文件 or 也可以直接全部删除所有缓存的type
    //NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes   
                                               modifiedSince:dateFrom completionHandler:^{
                                                   // code
                                               }];
}

#pragma mark--------注册webView agent  UIWebView与WKWebView替换相应方法
-(void)registerUserAgent{
    UIWebView  *tempWebView=[[UIWebView alloc] init];
    NSString *oldAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    DeLog(@"-----agent:%@",oldAgent);
    struct utsname systemInfo;

    uname(&systemInfo);

    //NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    NSString *newAgent = [NSString stringWithFormat:@"%@_eu8def",oldAgent];
    NSDictionary *dictionary = [[NSDictionary alloc]
                                initWithObjectsAndKeys:newAgent, @"UserAgent", nil];

    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    [DataUtil saveDefaultInfo:newAgent Key:USERAGENT];
}
 ///注册用户通知设置
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {  // register to receive notifications
    [application registerForRemoteNotifications];
}

//错误日志打印
void uncaughtExceptionHandler(NSException *exception) {
    DeLog(@"异常名称 : %@ ----- 异常原因 : %@",exception.name, exception.reason);
}

#pragma mark 自定义方法
/**
 注册本地通知
 
 @param application
 */
-(void)setNotice:(UIApplication *)application{
    // 设置应用程序的图标右上角的数字
    [application setApplicationIconBadgeNumber:0];
    [JPUSHService resetBadge];
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }
}

/**
 第三方分享和登录初始化
 *  初始化RootViewController 退出登录所用
 */
- (void)goTabMain{
    TabBarController *vc=[[TabBarController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    nav.navigationBarHidden = YES;
    self.window.backgroundColor = COLOR_WHITE;//这个设置目的是让动画的时候不显示黑屏
    self.window.rootViewController = nav;
    [self.window makeKeyWindow];
    self.rootVC = vc;
}

- (void)goLogin{
    LoginVC *vc=[[LoginVC alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    self.window.backgroundColor = COLOR_WHITE;//这个设置目的是让动画的时候不显示黑屏
    self.window.rootViewController = nav;
    nav.navigationBarHidden = YES;
    [self.window makeKeyWindow];
    self.rootVC = vc;
}
/**
 键盘管理
 */
- (void)initKeyboardManager {
    IQKeyboardManager *manager=[IQKeyboardManager sharedManager];
    manager.enable=YES;
    manager.shouldResignOnTouchOutside=YES;
    manager.enableAutoToolbar = YES;
    manager.shouldShowTextFieldPlaceholder = false;
    manager.shouldHidePreviousNext=YES;
}
/**
 检测网络连接状态
 */
- (void)checkNetWorkConnectStatus {
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                self.networkStatus=status;
                //[[NSNotificationCenter defaultCenter] postNotificationName:NET_CHANGE_NOTIFICATION object:@{@"status":@(AFNetworkReachabilityStatusUnknown)}];
                DeLog(@"未知网络");
            break;
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                 self.networkStatus=status;
                //[[NSNotificationCenter defaultCenter] postNotificationName:NET_CHANGE_NOTIFICATION object:@{@"status":@(AFNetworkReachabilityStatusNotReachable)}];
                [WToast showWithText:@"网络连接失败，请检查网络"];
                DeLog(@"没有网络(断网)");
            break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                 self.networkStatus=status;
                //[[NSNotificationCenter defaultCenter] postNotificationName:NET_CHANGE_NOTIFICATION object:@{@"status":@(AFNetworkReachabilityStatusReachableViaWWAN)}];
                DeLog(@"手机自带网络");
            break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                 self.networkStatus=status;
                //[[NSNotificationCenter defaultCenter] postNotificationName:NET_CHANGE_NOTIFICATION object:@{@"status":@(AFNetworkReachabilityStatusReachableViaWiFi)}];
                DeLog(@"WIFI");
            break;
        }
    }];
    // 3.开始监控
    [manager startMonitoring];
}
//---------支付模块开始
#pragma mark - 微信支付结果回调
- (void)onResp:(BaseResp*)resp {
    [ThirdPayUtil onResp:resp withWindow:self.window];
}

#pragma mark- application 代理
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    return [ThirdPayUtil application:app openURL:url options:options withDelegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [ThirdPayUtil application:application openURL:url sourceApplication:sourceApplication annotation:annotation withDelegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [ThirdPayUtil application:application handleOpenURL:url withDelegate:self];
}
/** <#注释#>*/
//--------支付模块结束
#pragma mark------初始化极光推送
-(void)initJPushServiceWithOptions:(NSDictionary *)launchOptions
{
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:kJPushIsProduction];
}
//定时器程序后台运行必要
- (void)applicationDidEnterBackground:(UIApplication *)application {
}

#pragma mark -------远程推送相关
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    DeLog(@"-------apnsInfo:%@",userInfo);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"APNSJUMP" object:nil userInfo:userInfo];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    application.applicationIconBadgeNumber = 0;
     [JPUSHService resetBadge];
    //
    [[NSNotificationCenter defaultCenter] postNotificationName:@"APNSJUMP" object:nil userInfo:userInfo];
    [JPUSHService handleRemoteNotification:userInfo];
    
       //AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);//震动
    //    completionHandler(UIBackgroundFetchResultNewData);
    
}
//推送设置
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //MT DEL +++++
        //[[EMClient sharedClient] bindDeviceToken:deviceToken];
        //MT DEL -----
    });
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">"
                                                                             withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [JPUSHService registerDeviceToken:deviceToken];
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    if ([self.rootVC isKindOfClass:UITabBarController.class]){
        UITabBarController *tabVC = (UITabBarController*)self.rootVC;
        PublicVC *vc = tabVC.viewControllers.firstObject;
        //[vc gotoPageWithModule:notification.userInfo[@"Module"] andTitle:nil andParam:notification.userInfo[@"paramStr"] andExtend:nil andTag:nil];
        return;
    }
    //[self.rootVC.navigationController.viewControllers.lastObject gotoPageWithModule:notification.userInfo[@"Module"] andTitle:nil andParam:notification.userInfo[@"paramStr"] andExtend:nil andTag:nil];
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    /**
     * 统计推送打开率3
     */
}

#pragma mark 处理内存警告
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    
}

//当程序复原时
- (void)applicationDidBecomeActive:(UIApplication *)application {
     application.applicationIconBadgeNumber=0;
    [JPUSHService resetBadge];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//当有电话进来或者锁屏，这时你的应用程会挂起
- (void)applicationWillResignActive:(UIApplication *)application {
    DeLog(@"applicationWillResignActive");
    [[NSNotificationCenter defaultCenter]postNotificationName:@"applicationWillResignActive" object:nil];
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

@end
